# -*- coding: utf-8 -*-
import datetime
import tornado
import tornado.web
import tcelery
from cache.topic_gallery_cache import refresh_topic_gallery_cache
from views.cms.cms_base import admin_required, cms_login, BaseHandler
from tasks.cms import update_all


try:
    import ujson as json
except:
    import json
from controls import mongo
from controls import data_topic_title_mysql
from controls import data_topic_gallery_mysql
from controls import data_topic_note_mysql
from controls import data_topic_note_img_mysql
from controls import data_manage_user_mysql
from controls import data_user_feed_mysql
from controls import data_city_base_mysql
from controls import data_message_system_content_mysql
from utils.file_util import file_upload
from utils import log
from config import etc


class ManageTopicHandler(BaseHandler):
    @admin_required
    def get(self):
        self.render('cms2/topic.html')
        return

    @admin_required
    def post(self):
        provid = self.get_argument('provid')
        title = self.get_argument('title')
        summary = self.get_argument('summary')

        if not (provid and title and summary):
            res = {'ret': 1, 'msg': 'param error'}
            self.write(json.dumps(res))
            self.finish()
            return

        topicid = mongo.count_topicid()

        file = self.request.files['file'][0]
        file_res = file_upload(file)

        if not (file_res and file_res['ret'] == 0):
            res = {'ret': 1, 'msg': '保存图片失败'}
            self.write(json.dumps(res))
            self.finish()
            return

        new_item = {
            'topicid': topicid,
            'title': title,
            'summary': summary,
            'hot': 0,
            'cityid': 0,
            'provid': int(provid),
            'imgid': file_res['res']['imgid'],
        }

        if not data_topic_title_mysql.add_topic_title_item(new_item):
            res = {'ret': 1, 'msg': 'add error'}
            self.write(json.dumps(res))
            self.finish()
            return

        res = {'ret': 0, 'msg': '保存成功'}
        self.write(json.dumps(res))
        self.finish()
        return


class ManageTopicGalleryHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/gallery.html')

    @admin_required
    def post(self):
        try:
            provid = self.get_argument('provid', None)

            if provid is None:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            gallery_list = data_topic_gallery_mysql\
                .get_topic_gallery_by_provid(provid)

            res = {'ret': 0, 'msg': '成功', 'res': gallery_list}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': '失败'}
            self.write(json.dumps(res))
            self.finish()
            return


class GalleryHandler(BaseHandler):
    @admin_required
    def get(self):
        try:
            provid = self.get_argument('provid', None)

            if provid is None:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            gallery_list = data_topic_gallery_mysql\
                .get_topic_gallery_by_provid(provid)

            res = {'ret': 0, 'msg': '成功', 'res': gallery_list}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': '失败'}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicGalleryAddHandler(BaseHandler):
    @admin_required
    def post(self):
        try:
            provid = self.get_argument('provid', None)
            gallery_info_string = self.get_argument('gallery')

            if provid is None or not gallery_info_string:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            gallery_info_list = json.loads(gallery_info_string)

            # 删除原来的
            data_topic_gallery_mysql.del_topic_gallery_item_by_provid(provid)

            # 增加新的
            for idx, gallery_info in enumerate(gallery_info_list):
                gallery_info['seq'] = idx
                gallery_info['provid'] = provid
                data_topic_gallery_mysql.add_topic_gallery_item(gallery_info)

            res = {'ret': 0, 'msg': '保存成功'}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicGalleryRefreshHandler(BaseHandler):
    @admin_required
    def post(self):
        try:
            provid = self.get_argument('provid', None)

            if provid is None:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            refresh_topic_gallery_cache(provid)

            res = {'ret': 0, 'msg': '保存成功'}
            self.write(json.dumps(res))
            self.finish()
            return
        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class TopicNoteHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/note.html')


class UserFakeHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/fake_user.html')


class UserNormalHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/normal_user.html')


class UserBlackHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/black_user.html')


class TopicNotePubHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/note_pub.html')


class FeedbackHandler(BaseHandler):
    @admin_required
    def get(self):
        return self.render('cms2/feedback.html')


class TopicNoteDelHandler(BaseHandler):
    @admin_required
    def post(self):
        try:
            noteid = self.get_argument('noteid')

            if not noteid:
                res = {'ret': 1, 'msg': 'param error'}
                self.write(json.dumps(res))
                self.finish()
                return

            note = data_topic_note_mysql.get_topic_note_by_noteid(noteid)
            if not note:
                res = {'ret': 1, 'msg': 'get note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            userid = note['userid']

            if not data_user_feed_mysql.del_user_feed({
                'userid': userid,
                'optype': data_user_feed_mysql.USER_FEED_TYPE_NOTE_POST,
                'targetid': noteid,
            }):
                res = {'ret': 1, 'msg': 'delete manage feed error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_img_mysql\
                    .delete_topic_note_img_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete img error'}
                self.write(json.dumps(res))
                self.finish()
                return

            if not data_topic_note_mysql\
                    .delete_topic_note_by_noteid(noteid):
                res = {'ret': 1, 'msg': 'delete note error'}
                self.write(json.dumps(res))
                self.finish()
                return

            res = {'ret': 0, 'msg': 'success'}
            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class SigninHandler(BaseHandler):
    def get(self):
        self.render('cms2/signin.html')
        return

    def post(self):
        try:
            username = self.get_argument('username')
            password = self.get_argument('password')

            if not (username and password):
                log.i('params fetching error')
                res = {
                    'ret': 1,
                    'msg': '输入错误',
                }

                self.write(json.dumps(res))
                self.finish()
                return

            manage_user = data_manage_user_mysql.get_manage_user_by_username(username)

            if manage_user and manage_user['password'] == password.strip(' \t\n\r'):
                expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
                cms_login(self, manage_user, expires)
                res = {
                    'ret': 0,
                    'msg': '登录成功',
                }

                self.write(json.dumps(res))
                self.finish()
            else:
                res = {
                    'ret': 1,
                    'msg': '输入错误',
                }
                self.write(json.dumps(res))
                self.finish()
                return

        except Exception as e:
            log.i(e)
            res = {'ret': 1, 'msg': etc.err_500}
            self.write(json.dumps(res))
            self.finish()
            return


class CityUpdateHandler(BaseHandler):
    def get(self):
        all_city = data_city_base_mysql.get_city_all_by_bg()

        self.render('cms2/city_update.html', city_info_list=all_city)


tcelery.setup_nonblocking_producer()


class CityUpdateAllHandler(BaseHandler):
    @tornado.web.asynchronous
    def post(self):
        try:
            cityid = self.get_argument('city_id')

            update_all.apply_async(args=[cityid], callback=self.on_success)

        except Exception as e:
            log.exp(e)
            res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
            self.write(json.dumps(res))
            self.finish()
            return

    def on_success(self, response):
        # 获取返回的结果
        result = response.result
        self.write(json.dumps(result))
        self.finish()


# not user
class MessageSystemHandler(BaseHandler):
    def get(self):
        self.render('cms2/message_system.html')
        return


class MessageSystemAddHandler(BaseHandler):
    @admin_required
    def post(self):
        content = self.get_argument('content', None)

        if not content:
            res = {'ret': -1, 'msg': 'ng'}
            self.write(json.dumps(res))
            self.finish()
            return


class CityBaseAddHandler(BaseHandler):
    def format_bgcolor(self, color_str):
        color_len = len(color_str)
        if color_len == 6:
            return color_str + 'ff'
        elif color_len == 8:
            return color_str
        else:
            return False

    def post(self):
        try:
            cityid = self.get_argument('city_id', None)
            prov_id = self.get_argument('prov_id', None)
            name = self.get_argument('name', None)
            cname = self.get_argument('cname', None)
            pos_x = self.get_argument('pos_x', None)
            pos_y = self.get_argument('pos_y', None)
            version = self.get_argument('version', None)
            # versioninfo = self.get_argument('versioninfo')
            bgcolortop = self.get_argument('bgcolortop', None)
            bgcolorend = self.get_argument('bgcolorend', None)
            if not (cityid and prov_id and name and cname
                    and pos_x and pos_y
                    and version
                    and bgcolortop and bgcolorend):
                res = {'idx': 0, 'ret': 2, 'msg': '有字段为空，处理不了啊', 'res':[]}
                self.write(json.dumps(res))
                self.finish()
                return

            bgcolorend = self.format_bgcolor(bgcolorend)
            bgcolortop = self.format_bgcolor(bgcolortop)

            if not bgcolortop or not bgcolorend:
                res = {'idx': 0, 'ret': 4, 'msg': '颜色是8位', 'res': []}
                self.write(json.dumps(res))
                self.finish()
                return

            result = data_city_base_mysql.add_city_base_item({
                'cityid': cityid,
                'provid': prov_id,
                'name': name,
                'cname': cname,
                'pos_x': pos_x,
                'pos_y': pos_y,
                'version': version,
                # 'versioninfo': versioninfo,
                'bgcolortop': bgcolortop,
                'bgcolorend': bgcolorend,
            })

            if result:
                res = {'idx': 0, 'ret': 0, 'msg': '新建成功', 'res': []}
            else:
                res = {'idx': 0, 'ret': 3, 'msg': '新建失败', 'res': []}

            self.write(json.dumps(res))
            self.finish()
            return

        except Exception as e :
            log.exp(e)
            res = {'idx': 0, 'ret': 1, 'msg': 'ng', 'res': []}
            self.write(json.dumps(res))
            self.finish()
            return


class SignoutHandler(BaseHandler):
    def get(self):
        pass

    def post(self):
        pass

class AuthHandler(BaseHandler):
    def get(self):
        if not self.current_user:
            self.redirect("/cms/signin")
            return
        else:
            self.redirect("/cms/topic")
            return